import { useRequest } from 'ahooks'
import {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useMemo,
  useRef,
  useState
} from 'react'

import { ModuleTitle, Tb } from '../../../BigScreenBase/ModuleTitle'
import { IDataAnalysisType } from '../../../BigScreenBase/data'
import {
  AssociationData,
  SwitchAndIntervalRef
} from '../../../BigScreenBase/interface'
import CommonLineChart from '../../Components/CommonLineChart'
import { getWarnTimeData } from '../../data'

interface LeftWarnTimePros {
  selectedAssociationItem: AssociationData
  onClearTimer: () => void
  onStartTimer: () => void
}

const timeLabelMap: [string, number[]][] = [
  ['凌晨', [0, 1, 2, 3, 4, 5]],
  ['早晨', [6, 7]],
  ['上午', [8, 9, 10]],
  ['中午', [11, 12]],
  ['下午', [13, 14, 15, 16, 17]],
  ['傍晚', [18, 19]],
  ['晚上', [20, 21, 22, 23]]
]

const warnTimeTabs = [
  { name: '近一年', value: 'y' },
  { name: '近一月', value: 'm' },
  { name: '近一周', value: 'w' }
]

const LeftWarnTime = forwardRef<SwitchAndIntervalRef, LeftWarnTimePros>(
  (props, ref) => {
    const {
      selectedAssociationItem: { key: entId },
      onClearTimer,
      onStartTimer
    } = props
    const [activeTab, setActiveTab] = useState('y')
    const timerRef = useRef<NodeJS.Timeout>()
    const lineChartRef = useRef<{ resize: () => void }>(null)

    const handleTabChange = (tab: Tb) => {
      if (tab.value === activeTab) return
      onClearTimer()
      const currType = tab.value as IDataAnalysisType
      setActiveTab(currType)
      onStartTimer()
    }

    const { data: warnTimeData = { xdata: [], ydata: [] }, run } = useRequest(
      async () => {
        const data = await getWarnTimeData({
          entId,
          timeType: activeTab
        })
        const transformData = timeLabelMap.reduce<{
          xdata: string[]
          ydata: number[]
        }>(
          (acc, [label, range]) => {
            const sum = range.reduce((sum, cur) => {
              const point = data.find((item) => Number(item.name) === cur)
              return sum + (point ? point!.value : 0)
            }, 0)
            acc.xdata.push(label)
            acc.ydata.push(sum)
            return acc
          },
          { xdata: [], ydata: [] }
        )
        return transformData
      },
      {
        refreshDeps: [activeTab, entId]
      }
    )

    const maxValue = useMemo(() => {
      const max = Math.max(...warnTimeData.ydata)
      return max < 5 ? 5 : max
    }, [warnTimeData])

    const startWarnDataInterval = () => {
      clearInterval(timerRef.current)
      timerRef.current = setInterval(() => {
        setActiveTab((key) => {
          const index = warnTimeTabs.findIndex((v) => v.value === key)
          const next = index === 2 ? 0 : index + 1
          return warnTimeTabs[next].value
        })
      }, 60000)
    }

    const clearWarnDataInterval = () => {
      clearInterval(timerRef.current)
      timerRef.current = undefined
    }

    useEffect(() => {
      startWarnDataInterval()
      return () => {
        clearWarnDataInterval()
      }
    }, [])

    useImperativeHandle(ref, () => {
      return {
        resize: () => lineChartRef.current?.resize(),
        intervalRefresh: () => {
          run()
          startWarnDataInterval()
        },
        switchAssociation: () => {
          startWarnDataInterval()
        }
      }
    })

    return (
      <div className="bigscreen-module ms-module" style={{ height: '205px' }}>
        <ModuleTitle
          title={'高风险时段'}
          tab={warnTimeTabs}
          activeKey={activeTab}
          tabChange={handleTabChange}
          onTitleTabMouseEnter={clearWarnDataInterval}
          onTitleTabMouseLeave={startWarnDataInterval}
        ></ModuleTitle>
        <div style={{ padding: '16px 24px 24px' }}>
          <CommonLineChart
            ref={lineChartRef}
            dataAnalysisList={warnTimeData}
            maxx={maxValue}
          />
        </div>
      </div>
    )
  }
)

export default LeftWarnTime
